<?php

namespace GuanChanghu\Library\Repositories\Message\MessageContent;


use GuanChanghu\Library\Contracts\Repositories\Order;
use GuanChanghu\Library\Contracts\Repositories\QueryRenderCallback;
use Illuminate\Database\Eloquent\Model as ModelAlias;
use GuanChanghu\Library\Contracts\Repositories\Query;
use GuanChanghu\Library\Facades\ModelQuery;
use GuanChanghu\Library\Repositories\Base\Facade;
use GuanChanghu\Library\Models\MessageContent as Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

/**
 * @author 管昌虎
 * Class MessageContentBase
 * @tag encryption free
 * @package GuanChanghu\Library\Repositories\Message\MessageContent
 * Created on 2023/4/2 11:43
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
class MessageContentBase extends Facade implements QueryRenderCallback, Order
{
    use \GuanChanghu\Library\Repositories\Base\Traits\Order;

    /**
     * @return Query
     */
    public function initModel(): Query
    {
        $modelConfig = config('guan-changhu.models.message_content');

        $this->model = new $modelConfig();

        return $this;
    }

    /**
     * @return Query
     */
    public function query(): Query
    {
        $condition = $this->attribute()->condition();
        $builder = $this->builder();

        $userId = (int)$condition->get('userId', 0);

        if ($userId) {
            $builder->with(['userMessage' => function ($query) use ($userId) {
                $query->where('user_id', $userId);
                $query->select([$query->getModel()->getKeyName(), 'message_content_id', 'read_num', 'jump_link_count']);
            }]);

            $builder->whereHasIn('userMessage', function ($query) use ($userId) {
                $query->where('user_id', $userId);
            });
        }

        if ($condition->has('client') && $condition->get('client')) {
            $builder->whereRaw('clients & ' . Model::clients((array)$condition->get('client')));
        }

        if ($condition->has('user') && $condition->get('user')) {
            $builder->whereHasIn('userMessages', function ($query) use ($condition) {
                ModelQuery::queryUserInfo($query, "user", $condition);
            });
        }

        ModelQuery::queryOptional($builder, $builder->getModel()->getKeyName(), $condition);
        ModelQuery::queryCongruence($builder, 'type', $condition);
        ModelQuery::queryOptional($builder, "title", $condition);
        ModelQuery::queryOptional($builder, "abstract", $condition);
        ModelQuery::queryTimeRange($builder, Str::camel(ModelAlias::CREATED_AT), $condition);

        return parent::query();
    }

    /**
     * @param ModelAlias $model
     * @return array|ModelAlias|Collection
     */
    public function callback(ModelAlias $model): array|ModelAlias|Collection
    {
        $condition = $this->attribute()->condition();

        $userId = (int)$condition->get('userId', 0);

        if (!$model['content'] && !$model['link'] && $userId && isset($model['userMessage']) && $model['userMessage']['readNum'] === 0) {
            // 没有正文 并且 没有跳转链接
            // 标记成已读
            $model->read();
        }

        if (isset($model['clients'])) {
            $model->setAttribute('clientLabelMany', $model['clientLabelMany']);
        }

        unset($model['content']);

        return $model;
    }
}
